package com.example.clock;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PerformanceHintManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
    private Calendar mC;
    private TextView tv;
    private Timer timer;
    private Handler mH;
    private String time;
    private DataBase dbHelper=new DataBase(this,"TimeList.db",null,2);
    protected  static SQLiteDatabase DB;
    protected  static int ids=1;
    protected static int offset=0;
    //但是时钟会慢一秒，不知道为什么，就这样吧，不想+1了
    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //数据库的实例化要在onCreate里实现，放到外面会报错，不知道为什么
        DB=dbHelper.getWritableDatabase();
        try{
            DB.execSQL("delete from list");
            DB.execSQL("update sqlite_sequence SET seq = 0 where name ='list'");
        }catch (Exception ignored) {

        }
        timer=new Timer();
        tv=findViewById(R.id.tvtime);
        try {
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    mC=Calendar.getInstance();//实例化一个日历
                    int hr=mC.get(Calendar.HOUR_OF_DAY)+8;
                    if(hr>24)hr-=24;
                    int min=mC.get(Calendar.MINUTE);
                    int sec=mC.get(Calendar.SECOND);
                    String time=String.format("%d:%02d:%02d",hr,min,sec);//将日历得到当前的时间转化为合乎习惯的字符串显示出来
                    Message mes=new Message();
                    mes.obj=time;
                    mes.what=0;
                    mH.sendMessage(mes);
                }
            },0,995);
        }catch (Exception e){
            Log.d("Timer","ERROR!!!!!!!");
            e.printStackTrace();
        }
        Button store=findViewById(R.id.store);
        store.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ContentValues timing=new ContentValues();
                int tem=ids-offset;
                timing.put("id",tem);
                timing.put("time",time);
                DB.insert("list",null, timing);
                ids++;
                timing.clear();
                Log.d("button","存储");
            }
        });
        Button tlist=findViewById(R.id.button2);
        tlist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(MainActivity.this, ListViewTest.class);
                startActivity(intent);
            }
        });
        //采用handler解决Only the original thread that created a view hierarchy can touch its views.的问题
        //不是很理解什么原理，多线程不是太了解，但确实解决问题了
        //更新：因为不能在子线程中更新UI，故用handler完成线程间的通信通知主线程更新ui
        //不能在子线程更新UI的原因是View是线程不安全的，而对其加锁又会使任务沉重响应速度变慢，故约定这么做
        try{mH=new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if(msg.what==-1) mH=null;
                else{
                    time=(String) msg.obj;
                    tv.setText(time);
                }
            }
        };}catch (Exception e){
            e.printStackTrace();
            Log.d("Handler","!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        }
    }
    public static SQLiteDatabase getDB(){
        return DB;
    }

    //尝试实现退出时删除数据库
    //寄了，留着吧不想删
    @Override
    public void finish() {
        super.finish();
        this.deleteDatabase("TimeList.db");
        Toast.makeText(this, "拜拜", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mH.removeCallbacksAndMessages(null);
    }
}